import { computed } from "vue";
import { useVtOptionsStore } from "@/store/modules/vt-options.store.js";
import { useConfigStore } from "@/store/modules/config.store.js";

/**
 * 格式化数字，最多保留四位小数
 * @param {number} value 要格式化的数字
 * @returns {number} 格式化后的数字
 */
const formatNumber = (value) => {
  if (typeof value !== "number" || isNaN(value)) {
    return 0;
  }
  // 保留最多4位小数，并去掉末尾的0
  return Number(parseFloat(value.toFixed(4)));
};

/**
 * 价格计算组合式函数
 * @param {Object} formData 表单数据
 * @returns {Object} 计算结果和相关函数
 */
export function usePriceCalculator(formData) {
  const vtOptionsStore = useVtOptionsStore();
  const configStore = useConfigStore();

  /**
   * 计算袋子面积 (平方米)
   * 根据袋型和尺寸计算
   */
  const excessSize = 20;
  const calculateArea = computed(() => {
    let { l, w, h } = formData;
    if (!l || !w) return 0;

    w = w + 2; //宽度加0.2
    l = l + 10; //长度加1

    // 基本面积计算：长 × 宽 (mm² 转换为 m²)
    let area = (l * w) / 1000000;
    // 根据袋型调整面积计算
    if (formData.bagType) {
      switch (formData.bagType) {
        case "自立袋":
          area = (l * (w * 2 + h)) / 1000000;
          break;
        case "三边封袋":
          area = (l * w * 2) / 1000000;
          break;
        case "中封袋":
          area = (l * w * 2) / 1000000;
          break;
        case "卷膜":
          area = (l * w) / 1000000;
          break;
        case "四边封袋":
          // area = ((l * 2 + (h + excessSize) * 2) * w * 2) / 1000000;
          area = (2 * w * (l + 2 * h)) / 1000000;
          break;
        case "中封风琴袋":
          area = (2 * w * (l + 2 * h)) / 1000000;
          break;
      }
    }

    return formatNumber(area);
  });

  /**
   * 根据材质和面积计算原材料重量 (kg)
   */
  const calculateMaterialWeight = async (quantity) => {
    if (!formData.material || formData.material.length === 0 || !calculateArea.value) {
      return 0;
    }

    let totalWeight = 0;
    for (const materialItem of formData.material) {
      // 解析材质名和厚度 "材质名-厚度"
      const [materialName, thickness] = materialItem.split("-");
      if (materialName && thickness) {
        const materialWeight = await calculateSingleMaterialWeight(
          materialName,
          thickness,
          quantity
        );
        totalWeight += materialWeight;
      }
    }

    return formatNumber(totalWeight);
  };

  /**
   * 计算总重量 (原材料重量 + 配件重量)
   */
  const calculateTotalWeight = async (quantity) => {
    const [materialWeight, accessoryResult] = await Promise.all([
      calculateMaterialWeight(quantity),
      calculateAccessoryPrice(quantity),
    ]);

    const totalWeight = materialWeight + accessoryResult.weight;

    return {
      materialWeight: materialWeight,
      accessoryWeight: accessoryResult.weight,
      totalWeight: formatNumber(totalWeight),
    };
  };

  /**
   * 计算单个材质的重量
   */
  const calculateSingleMaterialWeight = async (materialName, thickness, quantity) => {
    if (!calculateArea.value || !thickness || !quantity) {
      return 0;
    }

    try {
      // 获取材质选项数据，查找对应的密度信息
      const materialOptions = await vtOptionsStore.getMaterialOptions();
      // 查找匹配的材质选项
      let density = null; // 默认密度 kg/m³

      // 先尝试找完全匹配的材质+厚度
      const exactMatch = materialOptions.find(
        (opt) => opt.value === `${materialName}-${thickness}`
      );
      if (exactMatch && exactMatch.density) {
        density = exactMatch.density;
      } else {
        // 如果没有完全匹配，找同名材质的标准厚度来计算比值
        const materialMatch = materialOptions.find((opt) =>
          opt.value.startsWith(`${materialName}-`)
        );
        if (materialMatch) {
          // 从value中提取标准厚度
          const standardThickness = materialMatch.value.split("-")[1];
          if (standardThickness && materialMatch.density) {
            density = materialMatch.density;
          }
        }
      }

      if (!density) {
        return 0;
      }

      // 重量 = 面积 × 厚度 × 密度 × 数量 × 厚度比值
      const thicknessInM = parseFloat(thickness); // mm转换为米
      const materialWeight = calculateArea.value * thicknessInM * density * quantity;

      return formatNumber(materialWeight);
    } catch (error) {
      console.error("计算材质重量失败:", error);
      // 出错时使用默认计算方式
      return 0;
    }
  };

  /**
   * 根据材质重量计算材质价格
   */
  const calculateMaterialPrice = async (quantity) => {
    if (!formData.material || formData.material.length === 0) {
      return { price: 0, details: [] };
    }

    const materialOptions = await vtOptionsStore.getMaterialOptions();
    let totalPrice = 0;
    const details = [];

    for (const materialItem of formData.material) {
      const [materialName, thickness] = materialItem.split("-");
      // 先尝试精确匹配
      let option = materialOptions.find((opt) => opt.value === materialItem);

      // 如果精确匹配失败，寻找同材质的其他厚度
      if (!option) {
        option = materialOptions.find((opt) => opt.value.startsWith(`${materialName}-`));
        if (option) {
          console.warn(`材质 ${materialItem} 未找到精确匹配，使用替代规格: ${option.value}`);
        }
      }

      if (option && option.label) {
        // 从label中提取单价 "材质名 (厚度mm) (价格元/kg)"
        const priceMatch = option.label.match(/\(([0-9.]+)元\/kg\)/);
        if (priceMatch) {
          const unitPrice = parseFloat(priceMatch[1]);
          // 计算单个材质的重量（使用实际输入的厚度）
          const materialWeight = await calculateSingleMaterialWeight(
            materialName,
            thickness,
            quantity
          );
          const materialPrice = materialWeight * unitPrice;

          totalPrice += materialPrice;
          details.push({
            name: materialName,
            thickness: thickness, // 使用实际厚度
            weight: materialWeight,
            unitPrice: unitPrice,
            price: formatNumber(materialPrice),
            actualOption: option.value !== materialItem ? option.value : undefined, // 标记使用的替代规格
          });
        }
      } else {
        console.warn(`找不到材质选项: ${materialItem}`);
        console.warn(
          "可用的材质选项:",
          materialOptions.map((opt) => opt.value)
        );
      }
    }

    return { price: formatNumber(totalPrice), details };
  };

  /**
   * 根据袋型和数量计算制袋工艺价格
   */
  const calculateBagProcessPrice = async (quantity) => {
    if (!formData.bagProcess || !quantity) {
      return { price: 0, details: [] };
    }

    const bagTypeOptions = await vtOptionsStore.getBagTypeOptions(formData.type);
    const option = bagTypeOptions.find((opt) => opt.value === formData.bagProcess);

    if (option && option.label) {
      // 从label中提取单价 "工艺名(价格元/个)"
      const priceMatch = option.label.match(/\(([0-9.]+)元\/个\)/);
      if (priceMatch) {
        const unitPrice = parseFloat(priceMatch[1]);
        const price = quantity * unitPrice;

        return {
          price: formatNumber(price),
          details: [
            {
              name: formData.bagProcess,
              quantity: quantity,
              unitPrice: unitPrice,
              price: formatNumber(price),
            },
          ],
        };
      }
    }

    return { price: 0, details: [] };
  };

  /**
   * 根据复合工艺和面积计算价格
   */
  const calculateCompositePrice = async (quantity) => {
    if (!formData.compositeType || formData.compositeType.length === 0 || !quantity) {
      return { price: 0, details: [] };
    }

    const compositeOptions = await vtOptionsStore.getCompositeTypeOptions();
    let totalPrice = 0;
    const details = [];

    for (const compositeItem of formData.compositeType) {
      const option = compositeOptions.find((opt) => opt.value === compositeItem);

      if (option) {
        // 优先使用option中的unitPrice和minFee字段
        let unitPrice = option.unitPrice || 0;
        let minFee = option.minFee || 0;

        // 如果没有unitPrice字段，从label中提取单价 "工艺名(价格元/m²)"
        if (!unitPrice && option.label) {
          const priceMatch = option.label.match(/\(([0-9.]+)元\/m²\)/);
          if (priceMatch) {
            unitPrice = parseFloat(priceMatch[1]);
          }
        }

        if (unitPrice > 0) {
          const area = formatNumber(calculateArea.value * quantity);

          // 计算按面积的价格
          const areaPriceCalc = area * unitPrice;

          // 取按面积计算的价格和最低价格的较大值
          const compositePrice = Math.max(areaPriceCalc, minFee);

          totalPrice += compositePrice;
          details.push({
            name: compositeItem,
            area: area,
            unitPrice: unitPrice,
            minFee: minFee,
            areaPriceCalc: formatNumber(areaPriceCalc),
            price: formatNumber(compositePrice),
            usedMinFee: compositePrice === minFee, // 标识是否使用了最低价格
          });
        }
      }
    }

    return { price: formatNumber(totalPrice), details };
  };

  /**
   * 根据印刷颜色和面积计算价格
   */
  const calculateSurfacePrice = async (quantity) => {
    if (!formData.surfaceFee || formData.surfaceFee.length === 0 || !quantity) {
      return { price: 0, details: [] };
    }

    const surfaceOptions = await vtOptionsStore.getSurfaceFeeOptions();
    let totalPrice = 0;
    const details = [];

    for (const surfaceItem of formData.surfaceFee) {
      const option = surfaceOptions.find((opt) => opt.value === surfaceItem);

      if (option) {
        const unitPrice = option.unitPrice || 0;
        const minFee = option.minFee || 0;
        const area = formatNumber(calculateArea.value * quantity);

        // 计算按面积的价格
        const areaPriceCalc = area * unitPrice;

        // 取按面积计算的价格和最低价格的较大值
        const surfacePrice = Math.max(areaPriceCalc, minFee);

        totalPrice += surfacePrice;
        details.push({
          name: surfaceItem,
          area: area,
          unitPrice: unitPrice,
          minFee: minFee,
          areaPriceCalc: formatNumber(areaPriceCalc),
          price: formatNumber(surfacePrice),
          usedMinFee: surfacePrice === minFee, // 标识是否使用了最低价格
        });
      }
    }

    return { price: formatNumber(totalPrice), details };
  };

  /**
   * 根据配件长度计算价格和重量
   */
  const calculateAccessoryPrice = async (quantity) => {
    if (!formData.accessory || formData.accessory.length === 0) {
      return { price: 0, weight: 0, details: [] };
    }

    const accessoryOptions = await vtOptionsStore.getAccessoryOptions();
    let totalPrice = 0;
    let totalWeight = 0;
    const details = [];

    for (const accessoryItem of formData.accessory) {
      // 解析配件名和数量 "配件名-数量"
      const [accessoryName, length] = accessoryItem.split("-");
      const option = accessoryOptions.find((opt) => opt.value === accessoryName);

      if (option && option.label && length) {
        // 从label中提取单价 "配件名(价格元/m)" 或 "配件名(价格元/个)"
        const priceMatch = option.label.match(/\(([0-9.]+)元\/(m|个)\)/);
        if (priceMatch) {
          const unitPrice = parseFloat(priceMatch[1]);
          const sumLength = parseFloat(length) * quantity;
          const accessoryPrice = sumLength * unitPrice;

          // 计算配件重量：sumLength * weight (kg)
          const accessoryWeight = option.weight ? sumLength * option.weight : 0;

          totalPrice += accessoryPrice;
          totalWeight += accessoryWeight;

          details.push({
            name: accessoryName,
            quantity: quantity,
            length: parseFloat(length),
            sumLength: sumLength,
            unit: priceMatch[2],
            unitPrice: unitPrice,
            unitWeight: option.weight || 0, // 单位重量 kg/m 或 kg/个
            weight: formatNumber(accessoryWeight), // 总重量
            price: formatNumber(accessoryPrice),
          });
        }
      }
    }

    return {
      price: formatNumber(totalPrice),
      weight: formatNumber(totalWeight),
      details,
    };
  };

  /**
   * 计算指定数量的系统价格
   */
  const calculateSystemPrice = async (quantity, priceRatioCustom) => {
    if (!quantity || quantity <= 0) {
      return {
        totalPrice: 0,
        unitPrice: 0,
        details: {
          area: 0,
          materialWeight: 0,
          accessoryWeight: 0,
          totalWeight: 0,
          material: { price: 0, details: [] },
          bagProcess: { price: 0, details: [] },
          composite: { price: 0, details: [] },
          surface: { price: 0, details: [] },
          accessory: { price: 0, details: [] },
          boxFee: 0,
          boxCount: 0,
          boxPrice: 3.5,
          priceRatio: 0,
          baseTotalPrice: 0,
          extraLossFee: 0,
        },
      };
    }

    try {
      // 并行计算各项价格和配置加载
      const [materialResult, bagProcessResult, compositeResult, surfaceResult, accessoryResult] =
        await Promise.all([
          calculateMaterialPrice(quantity),
          calculateBagProcessPrice(quantity),
          calculateCompositePrice(quantity),
          calculateSurfacePrice(quantity),
          calculateAccessoryPrice(quantity),
        ]);

      // 加载配置数据
      if (!configStore.loaded) {
        await configStore.loadConfigs();
      }

      // 计算重量信息
      const weightResult = await calculateTotalWeight(quantity);

      // 计算纸箱费用：15kg一个纸箱，每个纸箱价格从配置获取
      const boxCount = Math.ceil(weightResult.totalWeight / 15);
      const boxPrice = configStore.getBagPrice || 3.5;
      const boxFee = boxCount * boxPrice;

      // 计算基础总价
      const baseTotalPrice =
        materialResult.price +
        bagProcessResult.price +
        compositeResult.price +
        surfaceResult.price +
        accessoryResult.price +
        boxFee;

      // 检查是否包含复合铝箔，计算额外损耗费用
      const hasAluminumFoil =
        formData.compositeType && formData.compositeType.some((item) => item === "复合铝箔");
      const extraLossRate = hasAluminumFoil ? 0.1 : 0; // 10% 额外损耗
      const extraLossFee = baseTotalPrice * extraLossRate;

      // 使用传入的价格比例配置
      const priceRatio = priceRatioCustom;

      // 计算单价（未加损耗前）
      const unitPriceBeforeLoss = quantity > 0 ? baseTotalPrice / quantity : 0;

      // 根据单价获取价格损耗比例
      let priceLossRate = 0;
      try {
        // 确保价格损耗数据已加载
        if (!configStore.priceLossData) {
          await configStore.loadPriceLossData();
        }
        priceLossRate = configStore.getPriceLossByPrice(unitPriceBeforeLoss);
      } catch (error) {
        console.error("获取价格损耗比例失败:", error);
        priceLossRate = 0;
      }

      // 计算价格损耗费用
      const priceLossFee = baseTotalPrice * (priceLossRate / 100);

      // 应用价格比例和损耗：1 + 值/100 + 价格损耗
      const totalPrice = baseTotalPrice * (1 + priceRatio / 100) + extraLossFee + priceLossFee;

      const unitPrice = quantity > 0 ? totalPrice / quantity : 0;

      return {
        totalPrice: formatNumber(totalPrice),
        unitPrice: formatNumber(unitPrice),
        details: {
          area: calculateArea.value,
          materialWeight: weightResult.materialWeight, // 原材料重量
          accessoryWeight: weightResult.accessoryWeight, // 配件重量
          totalWeight: weightResult.totalWeight, // 总重量
          material: materialResult,
          bagProcess: bagProcessResult,
          composite: compositeResult,
          surface: surfaceResult,
          accessory: accessoryResult,
          boxFee: formatNumber(boxFee), // 纸箱费用
          boxCount: boxCount, // 纸箱数量
          boxPrice: boxPrice, // 纸箱单价
          priceRatio: priceRatio, // 添加价格比例到详情中
          baseTotalPrice: formatNumber(baseTotalPrice), // 添加基础总价到详情中
          extraLossFee: formatNumber(extraLossFee), // 额外损耗费用
          hasAluminumFoil: hasAluminumFoil, // 是否包含复合铝箔
          extraLossRate: extraLossRate, // 额外损耗率
          unitPriceBeforeLoss: formatNumber(unitPriceBeforeLoss), // 未加损耗前的单价
          priceLossRate: priceLossRate, // 价格损耗比例
          priceLossFee: formatNumber(priceLossFee), // 价格损耗费用
        },
      };
    } catch (error) {
      console.error("计算系统价格失败:", error);
      return {
        totalPrice: 0,
        unitPrice: 0,
        details: {
          area: 0,
          materialWeight: 0,
          accessoryWeight: 0,
          totalWeight: 0,
          material: { price: 0, details: [] },
          bagProcess: { price: 0, details: [] },
          composite: { price: 0, details: [] },
          surface: { price: 0, details: [] },
          accessory: { price: 0, details: [] },
          boxFee: 0,
          boxCount: 0,
          boxPrice: 3.5,
          priceRatio: 0,
          baseTotalPrice: 0,
          extraLossFee: 0,
          unitPriceBeforeLoss: 0,
          priceLossRate: 0,
          priceLossFee: 0,
        },
      };
    }
  };

  return {
    calculateArea,
    calculateMaterialWeight,
    calculateTotalWeight,
    calculateSystemPrice,
  };
}
